package com.wzl.kgmusic;


import java.util.concurrent.locks.ReentrantLock;


public class DataBuffer {
	
	public static final String TAG = "DataBuffer";
	
	private byte[] mBuf;
	private int mCurPos = 0;
	private int mEndPos = 0;
	private int mBufSize = 0; 
	
	private final ReentrantLock _dataLock = new ReentrantLock();

	public DataBuffer(int size)
	{
		if(size <= 0)
			return;

		mBuf = new byte[size];
		mBufSize = size;
	}

	public int getLen()
	{
		_dataLock.lock();
		int len = mEndPos - mCurPos;

		if(len < 0)
			len = (len + mBufSize) % mBufSize;

		_dataLock.unlock();
		return len;
	}

	public int getLeft()
	{
		_dataLock.lock();
		int len = mBufSize - getLen();
		_dataLock.unlock();
		return len;
	}

	public boolean pushData(byte[] data)
	{
		if(getLeft() <= data.length)
		{
			int left = getLeft();
			throw new RuntimeException("pushData failt");
		}

		_dataLock.lock();
		if(mEndPos + data.length <= mBufSize)
		{
			System.arraycopy(data, 0, mBuf, mEndPos, data.length);
		}else{
			System.arraycopy(data, 0, mBuf, mEndPos, mBufSize-mEndPos);
			System.arraycopy(data, mBufSize-mEndPos, mBuf, 0, data.length - (mBufSize - mEndPos));
		}
		mEndPos = (mEndPos + data.length) % mBufSize;

		_dataLock.unlock();
		return true;
	}

	public boolean getData(byte[] data)
	{
		
		if(data == null || getLen() < data.length)
			return false;

//		_dataLock.lock();
		if(mCurPos + data.length <= mBufSize)
		{
			System.arraycopy(mBuf, mCurPos, data, 0, data.length);
		}else{
			System.arraycopy(mBuf, mCurPos, data, 0, mBufSize - mCurPos);
			System.arraycopy(mBuf, 0, data, mBufSize - mCurPos, data.length - (mBufSize - mCurPos));
		}

		mCurPos = (mCurPos + data.length) % mBufSize;

//		_dataLock.unlock();
		return true;
	}
}